package com.cakin.filter;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.cakin.constant.Constant.USER_SESSION;

/**
 * @ClassName: SysFilter
 * @Description: 实现用户登录后才能进入主页，用户注销后不能进入主页。
 * @Date: 2020/6/16
 * @Author: cakin
 */
public class SysFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 功能描述：用户权限过滤器
     *
     * @param req   请求
     * @param res   响应
     * @param chain 过滤器链
     * @throws IOException      IOException
     * @throws ServletException ServletException
     * @author cakin
     * @date 2020/6/16
     */
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        // 需要先转换一下
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        Object attribute = request.getSession().getAttribute(USER_SESSION);
        // 通过USER_SESSION判断用户是否登录
        if (attribute == null) {
            response.sendRedirect("/login.jsp");
        }
        chain.doFilter(request, res);
    }

    public void destroy() {

    }
}
